import 'package:get/get.dart';
import '../data/models/emotion_record.dart';
import '../data/models/analytics_models.dart';
import '../data/repositories/emotion_repository.dart' as emotion_repo;
import '../data/repositories/emotion_repository_impl.dart' as emotion_impl;
import '../data/repositories/media_repository.dart' as media_repo;
import '../data/repositories/media_repository_impl.dart' as media_impl;

/// 情绪记录控制器
/// Emotion record controller
class EmotionController extends GetxController {
  final emotion_repo.EmotionRepository _emotionRepository = emotion_impl.EmotionRepositoryImpl();
  final media_repo.MediaRepository _mediaRepository = media_impl.MediaRepositoryImpl();

  // 响应式状态变量
  // Reactive state variables
  final RxList<EmotionRecord> _allRecords = <EmotionRecord>[].obs;
  final RxList<EmotionRecord> _todayRecords = <EmotionRecord>[].obs;
  final RxList<EmotionRecord> _filteredRecords = <EmotionRecord>[].obs;
  final Rx<EmotionRecord?> _currentRecord = Rx<EmotionRecord?>(null);
  final RxBool _isLoading = false.obs;
  final RxString _errorMessage = ''.obs;
  final RxInt _totalRecords = 0.obs;
  final RxInt _consecutiveDays = 0.obs;
  final RxBool _hasTodayRecord = false.obs;

  // Getters for accessing reactive state
  List<EmotionRecord> get allRecords => _allRecords;
  List<EmotionRecord> get todayRecords => _todayRecords;
  List<EmotionRecord> get filteredRecords => _filteredRecords;
  EmotionRecord? get currentRecord => _currentRecord.value;
  bool get isLoading => _isLoading.value;
  String get errorMessage => _errorMessage.value;
  int get totalRecords => _totalRecords.value;
  int get consecutiveDays => _consecutiveDays.value;
  bool get hasTodayRecord => _hasTodayRecord.value;

  @override
  void onInit() {
    super.onInit();
    // 初始化时加载数据
    // Load data on initialization
    loadAllRecords();
    loadTodayRecords();
    loadStatistics();
  }

  /// 加载所有情绪记录
  /// Load all emotion records
  Future<void> loadAllRecords() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final records = await _emotionRepository.getAllRecords();
      _allRecords.assignAll(records);
      _filteredRecords.assignAll(records);
    } catch (e) {
      _errorMessage.value = '加载记录失败: ${e.toString()}';
      Get.snackbar('错误', '加载记录失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载今日情绪记录
  /// Load today's emotion records
  Future<void> loadTodayRecords() async {
    try {
      final records = await _emotionRepository.getTodayRecords();
      _todayRecords.assignAll(records);
      _hasTodayRecord.value = records.isNotEmpty;
    } catch (e) {
      _errorMessage.value = '加载今日记录失败: ${e.toString()}';
    }
  }

  /// 加载统计信息
  /// Load statistics
  Future<void> loadStatistics() async {
    try {
      final count = await _emotionRepository.getRecordCount();
      final consecutive = await _emotionRepository.getConsecutiveRecordingDays();
      
      _totalRecords.value = count;
      _consecutiveDays.value = consecutive;
    } catch (e) {
      _errorMessage.value = '加载统计信息失败: ${e.toString()}';
    }
  }

  /// 根据ID获取情绪记录
  /// Get emotion record by ID
  Future<void> loadRecordById(String id) async {
    try {
      _isLoading.value = true;
      final record = await _emotionRepository.getRecordById(id);
      _currentRecord.value = record;
    } catch (e) {
      _errorMessage.value = '加载记录详情失败: ${e.toString()}';
      Get.snackbar('错误', '加载记录详情失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 添加新的情绪记录
  /// Add new emotion record
  Future<String?> addRecord(EmotionRecord record) async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final id = await _emotionRepository.insertRecord(record);
      
      // 重新加载数据
      // Reload data
      await loadAllRecords();
      await loadTodayRecords();
      await loadStatistics();
      
      Get.snackbar('成功', '情绪记录已保存', snackPosition: SnackPosition.BOTTOM);
      return id;
    } catch (e) {
      _errorMessage.value = '保存记录失败: ${e.toString()}';
      Get.snackbar('错误', '保存记录失败', snackPosition: SnackPosition.BOTTOM);
      return null;
    } finally {
      _isLoading.value = false;
    }
  }

  /// 更新情绪记录
  /// Update emotion record
  Future<bool> updateRecord(EmotionRecord record) async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      await _emotionRepository.updateRecord(record);
      
      // 重新加载数据
      // Reload data
      await loadAllRecords();
      await loadTodayRecords();
      
      Get.snackbar('成功', '情绪记录已更新', snackPosition: SnackPosition.BOTTOM);
      return true;
    } catch (e) {
      _errorMessage.value = '更新记录失败: ${e.toString()}';
      Get.snackbar('错误', '更新记录失败', snackPosition: SnackPosition.BOTTOM);
      return false;
    } finally {
      _isLoading.value = false;
    }
  }

  /// 删除情绪记录
  /// Delete emotion record
  Future<bool> deleteRecord(String id) async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      // 先删除关联的媒体文件
      // Delete associated media files first
      await _mediaRepository.deleteMediaFilesByRecordId(id);
      
      // 删除记录
      // Delete record
      await _emotionRepository.deleteRecord(id);
      
      // 重新加载数据
      // Reload data
      await loadAllRecords();
      await loadTodayRecords();
      await loadStatistics();
      
      Get.snackbar('成功', '情绪记录已删除', snackPosition: SnackPosition.BOTTOM);
      return true;
    } catch (e) {
      _errorMessage.value = '删除记录失败: ${e.toString()}';
      Get.snackbar('错误', '删除记录失败', snackPosition: SnackPosition.BOTTOM);
      return false;
    } finally {
      _isLoading.value = false;
    }
  }

  /// 批量删除情绪记录
  /// Batch delete emotion records
  Future<bool> deleteRecords(List<String> ids) async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      // 删除关联的媒体文件
      // Delete associated media files
      for (final id in ids) {
        await _mediaRepository.deleteMediaFilesByRecordId(id);
      }
      
      // 批量删除记录
      // Batch delete records
      await _emotionRepository.deleteRecords(ids);
      
      // 重新加载数据
      // Reload data
      await loadAllRecords();
      await loadTodayRecords();
      await loadStatistics();
      
      Get.snackbar('成功', '已删除 ${ids.length} 条记录', snackPosition: SnackPosition.BOTTOM);
      return true;
    } catch (e) {
      _errorMessage.value = '批量删除失败: ${e.toString()}';
      Get.snackbar('错误', '批量删除失败', snackPosition: SnackPosition.BOTTOM);
      return false;
    } finally {
      _isLoading.value = false;
    }
  }

  /// 根据日期范围筛选记录
  /// Filter records by date range
  Future<void> filterRecordsByDateRange(DateTime startDate, DateTime endDate) async {
    try {
      _isLoading.value = true;
      final records = await _emotionRepository.getRecordsByDateRange(
        startDate: startDate,
        endDate: endDate,
      );
      _filteredRecords.assignAll(records);
    } catch (e) {
      _errorMessage.value = '筛选记录失败: ${e.toString()}';
    } finally {
      _isLoading.value = false;
    }
  }

  /// 搜索情绪记录
  /// Search emotion records
  Future<void> searchRecords({
    required String keyword,
    EmotionType? emotionType,
    DateRange? dateRange,
  }) async {
    try {
      _isLoading.value = true;
      final records = await _emotionRepository.searchRecords(
        keyword: keyword,
        emotionType: emotionType,
        dateRange: dateRange,
      );
      _filteredRecords.assignAll(records);
    } catch (e) {
      _errorMessage.value = '搜索记录失败: ${e.toString()}';
    } finally {
      _isLoading.value = false;
    }
  }

  /// 重置筛选条件
  /// Reset filter conditions
  void resetFilter() {
    _filteredRecords.assignAll(_allRecords);
  }

  /// 清空所有数据
  /// Clear all data
  Future<bool> clearAllData() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      await _emotionRepository.clearAllData();
      
      // 清空本地状态
      // Clear local state
      _allRecords.clear();
      _todayRecords.clear();
      _filteredRecords.clear();
      _currentRecord.value = null;
      _totalRecords.value = 0;
      _consecutiveDays.value = 0;
      _hasTodayRecord.value = false;
      
      Get.snackbar('成功', '所有数据已清空', snackPosition: SnackPosition.BOTTOM);
      return true;
    } catch (e) {
      _errorMessage.value = '清空数据失败: ${e.toString()}';
      Get.snackbar('错误', '清空数据失败', snackPosition: SnackPosition.BOTTOM);
      return false;
    } finally {
      _isLoading.value = false;
    }
  }

  /// 导出所有数据
  /// Export all data
  Future<Map<String, dynamic>?> exportAllData() async {
    try {
      _isLoading.value = true;
      return await _emotionRepository.exportAllData();
    } catch (e) {
      _errorMessage.value = '导出数据失败: ${e.toString()}';
      Get.snackbar('错误', '导出数据失败', snackPosition: SnackPosition.BOTTOM);
      return null;
    } finally {
      _isLoading.value = false;
    }
  }

  /// 刷新数据
  /// Refresh data
  Future<void> refreshData() async {
    await Future.wait([
      loadAllRecords(),
      loadTodayRecords(),
      loadStatistics(),
    ]);
  }

  /// 清除错误信息
  /// Clear error message
  void clearError() {
    _errorMessage.value = '';
  }

  /// 设置当前记录
  /// Set current record
  void setCurrentRecord(EmotionRecord? record) {
    _currentRecord.value = record;
  }
}